<template>
  <div>
    <van-cell v-for="(item, i) in list" :key="i">
      <template #title>
        <div
          v-html="heightLight(item)"
          @click="$emit('suggestClick', item)"
        ></div>
      </template>
    </van-cell>
  </div>
</template>

<script>
import { searchSuggest } from '@/api/user.js'
export default {
  name: 'SearchSuggest',
  props: {
    value: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      timer: null,
      list: []
    }
  },
  watch: {
    value: {
      handler () {
        if (this.timer) {
          clearTimeout(this.timer)
        }
        this.timer = setTimeout(() => {
          this.searchSuggest()
        }, 300)
      },
      immediate: true
    }
  },
  methods: {
    async searchSuggest () {
      if (this.value === '') {
        return
      }
      const res = await searchSuggest({
        q: this.value
      })
      this.list = res.data.options
    },
    // 高亮
    heightLight (val) {
      const reg = new RegExp(this.value, 'gi')
      return val.replace(reg, `<span style='color: red'>${this.value}</span>`)
    }
  }
}
</script>

<style></style>
